/*
 * @Descripttion: 自定义表单验证方法
* @param { $formData } <el-form :model="formData"></el-form>
 * @return { $formEl } <el-form ref="formEl"></el-form>
 * @Author: yeming
 * @Date: 2018-06-05 15:51:42
 */

import Vue from 'vue';

const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/;
const errorText = "6-20位，且必须包含字母和数字！";
const customValiate = {
  install (Vue) {
    Vue.prototype.$verify = {
      password: (value, callback, $formData, $formEl) => {
        if (value) {
          value = value.trim();
          if (!regex.test(value)) {
            return callback(new Error(errorText));
          } else {
            return callback();
          }
        } else { // 不能为空
          return callback(new Error(errorText));
        }
      },
      newPassword: (value, callback, $formData, $formEl) => {
        if (value) {
          value = value.trim();
          if (!regex.test(value)) {
            return callback(new Error(errorText));
          } else if ($formData.password === $formData.newPassword) {
            return callback(new Error("新密码与原密码相同！"));
          } else {
            return callback();
          }
        } else {
          return callback(new Error(errorText));
        }
      },
      confirmPassword: (value, callback, $formData, $formEl) => {
        if (value) {
          value = value.trim();
          if (!regex.test(value)) {
            return callback(new Error(errorText));
          } else if ($formData.confirmPassword !== $formData.newPassword) {
            return callback(new Error("两次输入密码不一致！"));
          } else {
            return callback();
          }
        } else {
          return callback(new Error(errorText));
        }
      }
    };
  }
};
Vue.use(customValiate);
